package top.fyxxxx.downloader.utils;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.StrictMode;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.MimeTypeMap;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import top.fyxxxx.downloader.Activities.MainActivity;
import top.fyxxxx.downloader.R;
import top.fyxxxx.downloader.Service.MyService;

public class HistoryAdapter extends BaseAdapter {
    private Context context;
    private List<History> historyList;
    private Map<String,DownloadTask>map;
    private ListView listView;
    private SqlUtil sqlUtil=SqlUtil.getInstance(context);
    public HistoryAdapter(Context context, Map<String,DownloadTask> map,List<History> historyList,ListView listView){
        this.context=context;
        this.historyList=historyList;
        this.map=map;
        this.listView=listView;
    }
    @Override
    public int getCount() {
        return historyList.size();
    }

    @Override
    public Object getItem(int position) {
        return historyList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, final View convertView, ViewGroup parent) {
        final History history=historyList.get(position);
        View v;
        ViewHolder holder;
        if(convertView==null){
            v= LayoutInflater.from(context).inflate(R.layout.history_item,null);
            holder=new ViewHolder();
            holder.download_image=(ImageView)v.findViewById(R.id.download_image);
            holder.download_name=(TextView)v.findViewById(R.id.download_name);
            holder.download_size=(TextView) v.findViewById(R.id.download_size);
            holder.download_date=(TextView)v.findViewById(R.id.download_date);
            holder.open_download_file=(Button)v.findViewById(R.id.open_download_file);
            v.setTag(holder);
        }
        else{
            v=convertView;
            holder=(ViewHolder)v.getTag();
        }
        holder.download_image.setImageResource(R.drawable.ic_action_apk);
        holder.download_name.setText(history.getFileName());
        String status=getStatue(history.getStatus());
        holder.download_size.setText(status+FormetFileSize(history.getDownloadedSize())+"/"+FormetFileSize(history.getFileSize()));
        holder.download_date.setText(longToDate(history.getDate()));
        if(history.getStatus()==0){
            holder.open_download_file.setText("打开");
            holder.open_download_file.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    openFile(history.getFilePath());
                }
            });
        }
        else if(history.getStatus()==1){
            holder.open_download_file.setText("暂停");
            holder.open_download_file.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    DownloadTask task=(DownloadTask)map.get(history.getFileName());
                    task.pause();
                }
            });
        }
        else if(history.getStatus()==2){
            holder.open_download_file.setText("继续");
                    holder.open_download_file.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            sqlUtil.deleteHistory(history);
                            DownloadTask task=(DownloadTask) map.get(history.getFileName());
                            if(task!=null)task.start();
                            else{
                                task = DownloadManager.getInstance(context).getTask(history.getUrl(),
                                        sqlUtil.getDownloadPath()+"/"+history.getFileName());
                                Intent intent=new Intent(context,MyService.class);
                                intent.putExtra("task",task.toString());
                                LocalSession.temp(task.toString(),task);
                                TaskListener listener=new TaskListener(context,history.getFileName(),sqlUtil.getDownloadPath()+"/"+history.getFileName(),history.getUrl(),listView,map,task);
                                task.addListener(listener);
                                context.startService(intent);
                            }
                        }
                    });
        }
        else if(history.getStatus()==3){
            holder.open_download_file.setText("重下");
            holder.open_download_file.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sqlUtil.deleteHistory(history);
                    File f=new File(history.getFilePath());
                    f.delete();
                    f=new File(history.getFilePath()+".download");
                    f.delete();
                    DownloadTask task = DownloadManager.getInstance(context).getTask(history.getUrl(),
                            sqlUtil.getDownloadPath()+"/"+history.getFileName());
                    Intent intent=new Intent(context,MyService.class);
                    intent.putExtra("task",task.toString());
                    LocalSession.temp(task.toString(),task);
                    context.startService(intent);
                }
            });
        }
        return v;
    }
    class ViewHolder{
        ImageView download_image;
        TextView download_name;
        TextView download_size;
        TextView download_date;
        Button open_download_file;
    }
    public static String longToDate(long lo){
        Date date = new Date(lo);
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sd.format(date);
    }
    public String FormetFileSize(long file) {
        DecimalFormat df = new DecimalFormat("#.0");
        String fileSizeString = "";
        if (file < 1024) {
            fileSizeString = df.format((double) file) + "B";
        } else if (file < 1048576) {
            fileSizeString = df.format((double) file / 1024) + "K";
        } else if (file < 1073741824) {
            fileSizeString = df.format((double) file / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) file / 1073741824) + "G";
        }
        return fileSizeString;
    }
    public String getStatue(int n){
        if(n==0){
            return new String("已完成");
        }
        else if(n==1){
            return new String ("正在下载");
        }
        else if(n==2){
            return new String("暂停");
        }
        else if(n==3){
            return new String ("失败");
        }
        else return null;
    }

    private void openFile(final String filePath)  {
        String ext = filePath.substring(filePath.lastIndexOf('.')).toLowerCase(Locale.US);
        StrictMode.VmPolicy defultVmPolicy = null;
        boolean isNeedMatch = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N;
        try {
            if (isNeedMatch) {
                defultVmPolicy = StrictMode.getVmPolicy();
                StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
                StrictMode.setVmPolicy(builder.build());
            }
            MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
            String temp = ext.substring(1);
            String mime = mimeTypeMap.getMimeTypeFromExtension(temp);
            mime = TextUtils.isEmpty(mime) ? "" : mime;
            Intent intent = new Intent();
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction(android.content.Intent.ACTION_VIEW);
            File file = new File(filePath);
            intent.setDataAndType(Uri.fromFile(file), mime);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(context.getApplicationContext(), "无法打开后缀名为." + ext + "的文件！",   Toast.LENGTH_LONG).show();
        } finally {
            if (isNeedMatch) StrictMode.setVmPolicy(defultVmPolicy);
        }
    }
}
